<template>
	<view class="container-check-box">
		<!-- <u-loading-page :loading="pageLoading"> -->
			<view class="hwq-content" style="height: 100%;">
				<navBar title="物资检查"></navBar>
				<u-search v-show="copyList.length > 0" v-model="searchText" class="search-box" :clearabled="false"
					placeholder="请输入关键字" :showAction="false" height="80rpx"></u-search>
				<scroll-view scroll-y="true"
					:style="{height:`calc(100vh - 320rpx - 164rpx}px)`}">
					<u-form :model="form" ref="form" :rules="rules" labelPosition="left" labelWidth="auto" class="form"
						v-show="copyList.length > 0">
						<u-form-item label="检查日期" prop="checkDate" borderBottom required @click="productionDateShow = true">
							<u-input v-model="form.checkDate" disabled disabledColor="#ffffff" border="none"></u-input>
							<u-icon slot="right" name="arrow-right" color="#A7AEBD" size="20"></u-icon>
						</u-form-item>
						<u-collapse :border="false" accordion ref="collapseRef">
							<template v-for="(it, index) in filterList">
								<u-collapse-item class="content_box" :key="index" :title="it.name" name="Docs guide"
									 >
									<view v-for="(item, index2) in it.child" class="child-box" :key="index2">
										<view class="con_top">
											<view class="con_top_name">
												<view class="top_title">
													{{ item.name }}</view>
												<view v-if="item.isRiskPeriod" class="state"><text>(风险)</text></view>
											</view>
											<view class="codes">{{ item.code }}</view>
										</view>
										<view class="con_bottom">
											<view class="con_unit">{{ item.materialCount || ''}}{{ item.units || '' }}</view>
											<view class="matching_box">
												<view class="aa"
													:class="{'matchingb':item.isMatch, 'matching_left':!item.isMatch}"
													@click="handleMatching(item,index2)">
													匹配
												</view>
												<view class="aa" :class="!item.isMatch ? 'matchingr' : 'matching_right'"
													@click="handleMatching(item,index2)">不匹配
												</view>
											</view>
										</view>
										<view class="missing-num" v-if="!item.isMatch">
											<view class="num-text">缺少数量</view>
											<u--input class="text-r" type="number" @input="inputVal(item)" placeholder="请输入"
												border="none" clearable placeholderStyle="fontSize:26rpx"
												v-model="item.missingQuantity"></u--input>
										</view>
									</view>
								</u-collapse-item>
							</template>
						</u-collapse>
			
						<view class="instructions_title">说明</view>
			
						<u-form-item borderBottom>
							<view class="form-item form-item-description">
								<u-textarea v-model="form.introductions" confirmType="send" placeholder="请输入内容"
									@blur="filedConditionBlur">
								</u-textarea>
								<record class="form-item-icon form-item-icon-voice" @setText="setFiledCondition"></record>
								<image mode="scaleToFill" class="form-item-icon form-item-icon-clear"
									src="/static/image/login/del1.png" @click="form.introductions = ''"></image>
							</view>
						</u-form-item>
			
						<u-form-item>
							<text class="require-text">上传照片</text>
							<u-upload :fileList="fileList1" name="1" @afterRead="afterRead" @delete="deletePic" multiple
								:maxCount="10" :previewFullImage="true" accept="image"></u-upload>
						</u-form-item>
					</u-form>
				</scroll-view>
			</view>
			<u-datetime-picker @cancel="productionDateShow = false" @confirm="productionDateConfirm" :minDate="lastTime"
				:maxDate="checkDate" :show="productionDateShow" v-model="checkDate" mode="date"></u-datetime-picker>
		<!-- </u-loading-page> -->
			<view class="footer-button">
				<view class="button-placeholder"></view>
				<view class="button-group">
					<button :loading="loading" @click="submit"  class="button-primary">提交</button>
				</view>
			</view>
		
	</view>
</template>

<script>
	import navBar from "@/components/navBar/navBar.vue"
	import searchCom from "@/components/searchCom.vue"
	import {
		saveMaterial,
		getCheckItem
	} from "@/api/project/projectOrg.js"
	import {
		uploadFile,
	} from '@/utils/request'
	import mixins from "@/utils/mixins.js";
	import uniCollapse from "./../components/uni-collapse/components/uni-collapse/uni-collapse.vue";
	
	export default {
		mixins: [mixins],
		name: "materialsInspection",
		components: {
			navBar,
			searchCom,
			uniCollapse
		},
		data() {
			return {
				loading: false,
				pageLoading:false,
				searchText: '',
				form: {
					checkDate: '',
					fieldCondition: '',
					siteId: '',
					stationId: '',
					riskState: '',
					worksCategory: '',
					introductions: ''
				},
				rules: {
					'checkDate': {
						type: 'string',
						required: true,
						message: '请选择生产日期',
						trigger: ['change', 'blur']
					}
				},
				checkDate: 0,
				productionDateShow: false,
				fileList1: [],
				lastList: [], //上一次的查询结果
				unitsList: [], //数量单位列表
				lastTime: 0, //上一次提交时间
				materialInspectionItems: [],
				filterList: [],
				copyList: [],
				// 几个盒子的高度,计算scroll-view的高度
				boxHeight: {
					navBarH: 40,
					searchH: 40,
					btnBoxH: 0,
				},
			}
		},
		watch: {
			searchText(newVal, oldVal) {
				if (newVal && newVal.trim()) {
					let list = JSON.parse(JSON.stringify(this.lastList))
					this.filterList = this.mapTree2(newVal, list)
				} else {
					this.$nextTick(() => {
						this.filterList = this.lastList
						this.$forceUpdate()
					})
				}
			}
		},
		onLoad(option) {
			this.form.siteId = option.siteId
			this.form.stationId = option.stationId
			this.form.riskState = option.riskState
			this.form.worksCategory = option.worksCategory
			this.form.checkDate = this.getDate(new Date())
			this.checkDate = new Date().getTime()

		},
		mounted() {
			this.getCheck()
		},

		methods: {
			mapTree2(value, arr) {
				let newarr = [];
				arr.forEach(element => {
					if (element.name.indexOf(value) > -1) { // 判断条件
						newarr.push(element);
					} else {
						if (element.child && element.child.length > 0) {
							let redata = this.mapTree2(value, element.child);
							if (redata && redata.length > 0) {
								let obj = {
									...element,
									child: redata
								};
								newarr.push(obj);
							}
						}
					}
				});
				return newarr;
			},
			//将相同类型的组装
			getSameType(arr) {
				let dataInfo = {};
				arr.forEach((item, index) => {
					let {
						type
					} = item;
					let bool = this.$store.getters.dictMap['material_category'].find(it => it.code === type) || {}
					if (!dataInfo[type]) {
						dataInfo[type] = {
							type,
							typeName: bool.name || null,
							child: []
						}
					}
					dataInfo[type].child.push(item);
				});
				return Object.values(dataInfo)
			},
			listToTree(data) {
				// * 先生成parent建立父子关系
				const obj = {}
				data.forEach(item => {
					obj[item.id] = item
				})
				const parentList = []
				data.forEach(item => {
					const parent = obj[item.parentId]
					if (parent) {
						// * 当前项有父节点
						parent.child = parent.child || []
						parent.child.push(item)
					} else {
						// * 当前项没有父节点 -> 顶层
						parentList.push(item)
					}
				})
				return parentList
			},
			//选择日期
			productionDateConfirm(val) {
				// console.log(this.lastTime, this.checkDate, val)
				// if (val.value < this.lastTime || val.value > this.checkDate) {
				// 	uni.showModal({
				// 		title: '选择正确的时间段！'
				// 	})
				// }

				this.form.checkDate = this.getDate(val.value)
				// console.log("value", this.form.checkDate)
				this.productionDateShow = false
			},
			//语言会来渲染
			filedConditionBlur(e) {
				this.filedConditionCursor = e.detail.cursor
			},
			setFiledCondition(text) {
				let index = this.filedConditionCursor || 0
				let str = this.formData.fieldCondition || ""
				this.filedConditionCursor += text.length
				text = str.slice(0, index) + text + str.slice(index)
				this.$set(this.formData, "fieldCondition", text)
			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				event.file.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'success',
						message: ''
					})
				})

			},
			inputVal(item) {
				if (item.missingQuantity != 0) {
					item.missingQuantity = item.missingQuantity.replace(/^(0+)|[^\d]+/g, '')
				}
			},
			//上一次提交结果数据
			async getCheck() {
				let projectId = uni.getStorageSync("isOwner")
				const _params = {
					siteId: this.form.siteId,
					projectId,
					keyword: this.searchText, // 项目名称、线路、区间/站点、提交人
					worksCategory: this.form.worksCategory, //工程类型
					riskstate: this.form.riskState, //工点状态
				}
				// this.pageLoading = true
				const res = await getCheckItem(_params)
				this.copyList = res.result
				this.lastList = this.listToTree(res.result); // list 转换成功的数据
				this.lastTime = res.result[0].lastSubmitted
				this.filterList = this.lastList
				// this.pageLoading = false
			},
			//点击匹配
			handleMatching(it, index) {
				let item = it
				item.isMatch = !item.isMatch
				item.isChange = !item.isChange
				item.missingQuantity = ''
				this.$nextTick(() => {
					this.$refs.collapseRef.init()
				})
				// console.log(this.filterList,'循环后filterList');
			},

			//提交按钮
			async submit() {
				let resultArr = []
				for (let it of this.lastList) {
					for (let item of it.child) {
						if (item.isChange) {
							item.isChange = 1
						} else {
							item.isChange = 0
						}
						if (item.isMatch) {
							item.isMatch = 1
						} else {
							item.isMatch = 0
							if (item.missingQuantity === '' || item.missingQuantity === undefined) {
								return uni.showToast({
									title: '缺失数量必填',
									icon: "none",
									mask: true
								})
							}
						}
						resultArr.push(item)
					}
				}

				let fileList = [...this.fileList1]
				if (fileList && fileList.length > 0) {
					if (this.loading) return
					this.loading = true
					uni.showLoading({
						title: '上传中',
						mask: true
					})
					for (let item of fileList) {
						let formData = {}
						if (this.form.docId) {
							formData.docId = this.form.docId
						}
						// this.form.siteId = this.siteId
						// #ifdef APP-PLUS || H5
							const obj = {
								url: "rest/doc/uploadDoc",
								formData,
								files: [{
									name: "attach",
									uri: item.url
								}]
							}
						// #endif
						
						// #ifdef MP-WEIXIN
							const obj = {
								url: "rest/doc/uploadDoc",
								formData,
								filePath: item.url
							}
						// #endif
						let data = await uploadFile(obj)
						let res = JSON.parse(data)
						if (!res.success) return
						this.form.docId = res.result.id
					}
					uni.hideLoading()
					this.form.materialInspectionItems = resultArr.filter(item => item.isMatch === 0 || item
						.isChange === 1)
					let isOwnerProjectId = uni.getStorageSync("isOwner")
					this.form.projectId = isOwnerProjectId || null
					let res = await saveMaterial(this.form)
					
					if (res.success) {
						uni.showToast({
							icon: 'success',
							title: "保存成功"
						})
						this.loading = false
					}
					uni.navigateBack()
				} else {
					this.$message("请上传图片")
					this.loading = false
				}
			}
		},
	}
</script>
<style lang="scss" scoped>
	.container-check-box {
		/* #ifdef MP-WEIXIN */
			padding-top: 200rpx;
		/* #endif */
	}
	.hwq-content {
		.form-item {
			width: 100%;
			position: relative;
		}

		.instructions_title {
			padding-top: 20rpx;
		}

		.form-item-description {
			.form-item-icon {
				width: 48rpx;
				height: 48rpx;
			}

			.form-item-icon-voice {
				position: absolute;
				top: 10rpx;
				right: 16rpx;
				z-index: 3;
			}

			.form-item-icon-clear {
				position: absolute;
				right: 16rpx;
				bottom: 10rpx;
				z-index: 2;
			}
		}

		.content_box {
			width: 100%;
			background: #fff;
			padding: 20rpx 0;
			border-bottom: 1px solid #eaebec;

			

			

			

			.form-item {
				width: 100%;
				position: relative;
				margin: 0 auto;
			}

			.form-item {
				width: 80%;
				position: relative;
				margin: 0 auto;
			}

			.form-item-description {
				.form-item-icon {
					width: 48rpx;
					height: 48rpx;
				}

				.form-item-icon-voice {
					position: absolute;
					top: 10rpx;
					right: 16rpx;
					z-index: 3;
				}

				.form-item-icon-clear {
					position: absolute;
					right: 16rpx;
					bottom: 10rpx;
					z-index: 2;
				}
			}
		}
	}

	.missing-num {
		display: flex;
		align-items: center;
		margin: 30rpx 0 10rpx;

		.num-text {
			font-size: 30rpx;
		}

		.num-text::before {
			content: '*';
			color: #e13e53;
		}

		/deep/ input {
			text-align: right !important;
		}
	}

	/deep/ .u-cell__body {
		padding: 15px 0 !important;

	}

	/deep/ .u-cell__title-text {
		font-weight: bold;
	}

	.outerbtn {
		height: 100rpx;

		.button {
			height: 92rpx;
			line-height: 92rpx;
			background: #2F80ED;
			color: #FFFFFF;
			text-align: center;
			font-size: 32rpx;
			position: fixed;
			bottom: 0;

		}
	}

	.require-text::before {
		content: '*';
		color: red;
	}
	.child-box {
		border-bottom: 1px solid #eaebec;
		padding: 18rpx;
		margin-left: 10rpx;
	}
	.con_top {
		display: flex;
		justify-content: space-between;
	
		.top_title {
			// width: 200px;
			font-size: 30rpx;
			min-width: 120px;
		}
	
		.codes {
			// max-width: 200px;
		}
	
		.con_top_name {
			display: flex;
			margin-bottom: 10rpx;
	
			.state {
				color: #f99c34;
				margin-left: 10rpx;
				min-width: 80rpx;
	
				span {
					color: #000;
				}
			}
		}
	}
	.con_bottom {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin: 16rpx 0;
	
		.con_unit {
			font-size: 30rpx;
		}
	
		
	}
	.matching_box {
		display: flex;
		justify-content: space-between;
	}
	.aa {
		padding: 10rpx 30rpx;
		border-radius: 6rpx;
		text-align: center;
		margin-left: 10rpx;
	}
	.matchingb {
		color: #fff;
		background: #2f80ed;
	}
	
	.matching_left {
		// width: 100rpx;
		color: #000;
		background: #d7d7d7;
	}
	
	.matchingr {
		// width: 100rpx;
		padding: 10rpx 30rpx;
		color: #fff;
		border-radius: 6rpx;
		text-align: center;
		background: #f59a23;
	}
	
	.matching_right {
		// width: 100rpx;
		padding: 10rpx 30rpx;
		color: #000;
		border-radius: 6rpx;
		text-align: center;
		background: #d7d7d7;
	}
	/deep/ .u-collapse-item {
		border-bottom: 1px solid #eaebec;
	}
</style>